/*
 * @Description: 用户规则权限 - 权限设置弹窗
 * @Author: Rfan
 * @Date: 2022-04-18 11:54:25
 * @LastEditTime: 2022-05-25 08:58:02
 */

import { Button, Form, Modal, Radio, Space } from 'antd';
import { FC, useCallback, useEffect } from 'react';
import type { ICommonDialog } from '@/interfaces/global';
import { jsonClone } from '@/utils';
import { useManageRuleContext } from '../../contexts/ManageRuleContext';

interface IRuleSettingDialogProps extends ICommonDialog {}

const RuleSettingDialog: FC<IRuleSettingDialogProps> = (props) => {
  const { visible, onClose } = props;
  console.log('rule v: ', visible);
  const { userRightsInfo, saveUserRightsFunc } = useManageRuleContext();
  // 解构id与权限列表配置
  const { entryId, operateRights } = userRightsInfo;
  // 解构权限列表与权限选项
  const { operateRights: rightList = [], operateRightsOption } = operateRights || {};

  const [form] = Form.useForm();

  const memoizedClose = useCallback(() => onClose(), []);

  useEffect(() => {
    if (visible && entryId) {
      const obj: any = {};
      for (let i = 0; i < rightList.length; i++) {
        const ele = rightList[i];
        obj[ele.index] = ele.value;
      }
      form.setFieldsValue(obj);
    }
  }, [visible]);

  const onCancel = () => {
    memoizedClose();
  };

  const saveRights = () => {
    form.submit();
  };

  const onFinish = (values: any) => {
    const operateRights = jsonClone(rightList);
    for (const key in values) {
      for (let i = 0; i < operateRights.length; i++) {
        const ele = operateRights[i];
        if (parseInt(ele.index, 10) === parseInt(key, 10)) {
          ele.value = values[key];
        }
      }
    }
    saveUserRightsFunc({ entryId, operateRights }).then(() => {
      memoizedClose();
    });
  };

  return (
    <Modal
      title="权限设置"
      visible={visible}
      width={400}
      destroyOnClose
      onCancel={onCancel}
      footer={[
        <Button key="close" onClick={onCancel}>
          取消
        </Button>,
        <Button key="save" type="primary" onClick={saveRights}>
          设置
        </Button>
      ]}
    >
      <Form form={form} onFinish={onFinish}>
        {rightList.map((item: any) => (
          <Form.Item name={item.index} label={item.name}>
            <Radio.Group>
              <Space>
                {operateRightsOption.map((option: any) => (
                  <Radio value={option.value}>{option.name}</Radio>
                ))}
              </Space>
            </Radio.Group>
          </Form.Item>
        ))}
      </Form>
    </Modal>
  );
};

export default RuleSettingDialog;
